package cn.exrick.xboot.modules.base.controller.manage;

import cn.exrick.xboot.common.annotation.AdminIntercept;
import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SnowFlakeUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.ApprovalInfo.utils.ApprovalInfoUtils;
import cn.exrick.xboot.modules.base.entity.*;
import cn.exrick.xboot.modules.base.service.*;
import cn.exrick.xboot.modules.base.service.mybatis.IUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @author Exrickx
 */
@Slf4j
@RestController
@Api(description = "角色管理接口")
@RequestMapping("/xboot/role")
@Transactional
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private RoleDepartmentService roleDepartmentService;

    @Autowired
    private StringRedisTemplate redisTemplate;

   /* private ApprovalInfoUtils approvalInfoUtils = new ApprovalInfoUtils();*/
    @Autowired
    private ApprovalInfoUtils  approvalInfoUtils;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getAllList",method = RequestMethod.GET)
    @ApiOperation(value = "获取全部角色")
    public Result<Object> roleGetAll(){

        List<Role> list = roleService.getAll();
        return new ResultUtil<Object>().setData(list);
    }

    @RequestMapping(value = "/getAllByPage",method = RequestMethod.GET)
    @ApiOperation(value = "分页获取非管理员（普通）角色")
    public Result<Page<Role>> getRoleByPage(@ModelAttribute PageVo page){

        System.out.println(page.getPageNumber()+"分页获取角色");
        Page<Role> list = roleService.findByType(CommonConstant.ROLE_TYPE_NORMAL,PageUtil.initPage(page));
        System.out.println(list.toString()+"分页获取角色");
        for(Role role : list.getContent()){
            // 角色拥有权限
            List<RolePermission> permissions = rolePermissionService.findByRoleId(role.getId());
            role.setPermissions(permissions);
            // 角色拥有数据权限
            List<RoleDepartment> departments = roleDepartmentService.findByRoleId(role.getId());
            role.setDepartments(departments);
        }
        return new ResultUtil<Page<Role>>().setData(list);
    }

    @RequestMapping(value = "/getAllAdminRole",method = RequestMethod.GET)
    @ApiOperation(value = "分页获取非管理员（普通）角色")
    public Result<List<Role>> getAllAdminRole(){


        List<Role> list = roleService.findByType(CommonConstant.ROLE_TYPE_ADMIN);
        System.out.println(list.toString()+"获取管理员角色");
        for(Role role : list){
            // 角色拥有权限
            List<RolePermission> permissions = rolePermissionService.findByRoleId(role.getId());
            role.setPermissions(permissions);
            // 角色拥有数据权限
            List<RoleDepartment> departments = roleDepartmentService.findByRoleId(role.getId());
            role.setDepartments(departments);
        }
        return new ResultUtil<List<Role>>().setData(list);
    }

    @RequestMapping(value = "/setDefault",method = RequestMethod.POST)
    @ApiOperation(value = "设置或取消默认角色")
    public Result<Object> setDefault(@RequestParam String id,
                                     @RequestParam Boolean isDefault){

        Role role = roleService.get(id);
        if(role==null){
            return new ResultUtil<Object>().setErrorMsg("角色不存在");
        }
        role.setDefaultRole(isDefault);
        roleService.update(role);
        return new ResultUtil<Object>().setSuccessMsg("设置成功");
    }

    @RequestMapping(value = "/editRolePerm",method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色分配菜单权限")
    public Result<Object> editRolePerm(@RequestParam String roleId,
                                       @RequestParam(required = false) String[] permIds){

        //删除其关联权限
        rolePermissionService.deleteByRoleId(roleId);
        //分配新权限
        for(String permId : permIds){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permId);
            rolePermissionService.save(rolePermission);
        }
        //手动批量删除缓存
        Set<String> keysUser = redisTemplate.keys("user:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplate.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);
        Set<String> keysUserPerm = redisTemplate.keys("userPermission:" + "*");
        redisTemplate.delete(keysUserPerm);
        Set<String> keysUserMenu = redisTemplate.keys("permission::userMenuList:*");
        redisTemplate.delete(keysUserMenu);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/editRoleDep",method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色分配数据权限")
    public Result<Object> editRoleDep(@RequestParam String roleId,
                                      @RequestParam Integer dataType,
                                      @RequestParam(required = false) String[] depIds){

        Role r = roleService.get(roleId);
        r.setDataType(dataType);
        roleService.update(r);
        // 删除其关联数据权限
        roleDepartmentService.deleteByRoleId(roleId);
        // 分配新数据权限
        for(String depId : depIds){
            RoleDepartment roleDepartment = new RoleDepartment();
            roleDepartment.setRoleId(roleId);
            roleDepartment.setDepartmentId(depId);
            roleDepartmentService.save(roleDepartment);
        }
        // 手动删除相关缓存
        Set<String> keys = redisTemplate.keys("department:" + "*");
        redisTemplate.delete(keys);
        Set<String> keysUserRole = redisTemplate.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);

        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @ApiOperation(value = "保存数据")
    public Result<Role> save(@ModelAttribute Role role){

        Role r = roleService.save(role);
        return new ResultUtil<Role>().setData(r);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiOperation(value = "更新数据")
    @AdminIntercept
    public Result<Role> edit(@ModelAttribute Role entity){

        Role r = roleService.update(entity);
        //手动批量删除缓存
        Set<String> keysUser = redisTemplate.keys("user:" + "*");
        redisTemplate.delete(keysUser);
        Set<String> keysUserRole = redisTemplate.keys("userRole:" + "*");
        redisTemplate.delete(keysUserRole);
        return new ResultUtil<Role>().setData(r);
    }

    @RequestMapping(value = "/delAllByIds/{ids}",method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    @AdminIntercept
    public Result<Object> delByIds(@PathVariable String[] ids){

        for(String id:ids){
            List<UserRole> list = userRoleService.findByRoleId(id);
            if(list!=null&&list.size()>0){
                return new ResultUtil<Object>().setErrorMsg("删除失败，包含正被用户使用关联的角色");
            }
        }
        for(String id:ids){
            roleService.delete(id);
            //删除关联菜单权限
            rolePermissionService.deleteByRoleId(id);
            //删除关联数据权限
            roleDepartmentService.deleteByRoleId(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }

    /**
     * @author njp
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/registAssessor",method = RequestMethod.POST)
    @ApiOperation(value = "注册审批员")
    public Result<Object> registAssessor(@Param("username") String username,@Param("password") String password ){
        //1.先查询接收到的用户名与密码是否在正确
        //在本地查询，是否为本地用户
        User user = userService.findByUsername(username);
        if (user != null) {
            /*if (!new BCryptPasswordEncoder().matches(password, user.getPassword())) {
                return new ResultUtil<Object>().setErrorMsg("用户名或密码错误");
            }*/
            //2.在表中t_user_role 表中插入我们写死在程序中的审批员的角色
            Date date = new Date();
            UserRole userRole=new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(CommonConstant.APPROVAL_ROLRID);
            userRole.setCreateTime(date);
            userRole.setUpdateTime(date);
            userRoleService.save(userRole);
        }else{
            return new ResultUtil<Object>().setErrorMsg("用户名或密码错误");
        }



        return new ResultUtil<Object>().setSuccessMsg("注册审批员成功");
    }

    /**
     * njp 20190725 新增微信登录方式的启用与禁用 end
     */
    @RequestMapping(value = "/getUserRoleByRoleId",method = RequestMethod.GET)
    @ApiOperation(value = "获取对应角色的user")
    public Result<List<UserRole>> getUserRoleByRoleId(){
        log.info("调用接口getUserRoleByRoleId，获取审批员角色的user");
        UserRole  userRole=new UserRole();
        //审批员的roleID
        userRole.setRoleId(CommonConstant.APPROVAL_ROLRID);
        List<UserRole> list = iUserRoleService.findUserRoleByRoleId(userRole);
        return new ResultUtil<List<UserRole>>().setData(list);
    }

    @RequestMapping(value = "/getUserRoleByUserId",method = RequestMethod.GET)
    @ApiOperation(value = "获取账户对应角色的role")
    public Result<List<UserRole>> getUserRoleByUserId(UserRole userRole){
        log.info("调用接口getUserRoleByUserId，获取账户对应角色的role");
        /*UserRole  userRole=new UserRole();
        userRole.setUserId("682265633886209");*/
        List<UserRole> list = iUserRoleService.findUserRoleByUserId(userRole);
        return new ResultUtil<List<UserRole>>().setData(list);
    }

    @RequestMapping(value = "/getUsernameByRoleId",method = RequestMethod.GET)
    @ApiOperation(value = "获取对应角色的role的username")
    public Result<List<User>> getUsernameByRoleId(){
        log.info("getUsernameByRoleId，获取对应角色的username");

       // List<User> usernamesByRoleId = iUserRoleService.findUsernamesByRoleId(CommonConstant.APPROVAL_ROLRID);
        List<User> usernamesByRoleId =approvalInfoUtils.getAPPROVAL();

        return new ResultUtil<List<User>>().setData(usernamesByRoleId);
    }

    @RequestMapping(value = "/getAdminUserByOrgId",method = RequestMethod.GET)
    @ApiOperation(value = "通过组织id获取管理员用户")
    public Result<List<User>> getAdminUserByOrgId(String orgid){
        //连表查询（查询出user中角色中有管理员角色的用户）

        return new ResultUtil<List<User>>().setData(null);
    }
    @RequestMapping(value = "/addAdminRole",method = RequestMethod.POST)
    @ApiOperation(value = "新增管理角色")
    public Result<Role> addAdminRole(@ModelAttribute Role role){
        role.setName("ROLE_ADMIN_"+ SnowFlakeUtil.getFlowIdInstance().nextId());
        //管理员角色
        role.setType(CommonConstant.ROLE_TYPE_ADMIN);
        Role r = roleService.save(role);
        return new ResultUtil<Role>().setData(r);
    }


}
